package com.pm.business.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageInfo;
import com.pm.business.domain.CurrentProject;
import com.pm.business.domain.ProjectPersonVo;
import com.pm.business.service.ICurrentProjectService;
import com.pm.common.constant.HttpStatus;
import com.pm.common.core.page.PageDomain;
import com.pm.common.core.page.TableSupport;
import com.pm.common.utils.DictUtils;
import com.pm.common.utils.PageUtils;
import com.pm.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.pm.common.annotation.Log;
import com.pm.common.core.controller.BaseController;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.enums.BusinessType;
import com.pm.business.domain.ProjectPerson;
import com.pm.business.service.IProjectPersonService;
import com.pm.common.utils.poi.ExcelUtil;
import com.pm.common.core.page.TableDataInfo;

/**
 * 基本资料管理Controller
 * 
 * @author zxl
 * @date 2022-05-05
 */
@RestController
@RequestMapping("/business/project_person")
public class ProjectPersonController extends BaseController
{
    @Autowired
    private IProjectPersonService projectPersonService;
    @Autowired
    private ICurrentProjectService currentProjectService;

    /**
     * 查询基本资料管理列表
     */
    @PreAuthorize("@ss.hasPermi('business:project_person:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProjectPerson projectPerson)
    {
        //added by gaojianhong 20220921 for 若依框架只会对startPage后第一个查询结果进行分页，对于处理后的list进行分页需要手工处理 start
        //startPage();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        //added by gaojianhong 20220921 for 若依框架只会对startPage后第一个查询结果进行分页，对于处理后的list进行分页需要手工处理 end

        List<ProjectPerson> list = projectPersonService.selectProjectPersonList(projectPerson);
        if(list!=null && list.size()>0){
            List<Long>personIds = new ArrayList<>();
            list.forEach(pp->{
                personIds.add(pp.getPersonId());
            });
            Map<Long,Long>lockedMap = new HashMap<Long,Long>();
            List<ProjectPerson>lockedPersonList = projectPersonService.selectLockedStatusByPersonIds(personIds);

            if (lockedPersonList != null && lockedPersonList.size() > 0) {
                lockedPersonList.forEach(pp -> {
                    lockedMap.put(pp.getPersonId(), pp.getPersonId());
                });
                list.forEach(pp -> {
                    if (lockedMap.get(pp.getPersonId()) != null) {
                        pp.setLocked(true);
                    }
                });
            }

            //added by gaojianhong for 人员锁定状态条件判断
            if (projectPerson.getLocked()!=null && projectPerson.getLocked() ) {
                list.removeIf(pp_obj -> pp_obj.getLocked()==null);
            }
            if (projectPerson.getLocked()!=null && !projectPerson.getLocked() ) {
                list.removeIf(pp_obj -> pp_obj.getLocked()!=null && pp_obj.getLocked());
            }
        }

        //added by gaojianhong 20220921 for 若依框架只会对startPage后第一个查询结果进行分页，对于处理后的list进行分页需要手工处理 start
        //获取处理好的list集合
        int num = list.size();
        list = list.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());

        //return getDataTable(list);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(num);
        return rspData;
        //added by gaojianhong 20220921 for 若依框架只会对startPage后第一个查询结果进行分页，对于处理后的list进行分页需要手工处理 end
    }
    @PreAuthorize("@ss.hasPermi('business:project_person:list')")
    @GetMapping("/applist")
    public TableDataInfo applist(ProjectPerson projectPerson)
    {
        projectPerson.setPersonType(DictUtils.getDictValue("pm_person_type",projectPerson.getPersonType()));
        projectPerson.setTitle(DictUtils.getDictValue("pm_person_title",projectPerson.getTitle()));
        String lockStatus = projectPerson.getLockStatus();
        Boolean locked =null;
        if(StringUtils.isNotEmpty(lockStatus)&&!StringUtils.equals(lockStatus,"锁定状态")){
            locked = StringUtils.equals(lockStatus,"已锁定")?true:false;
        }
        projectPerson.setLocked(locked);

        //added by gaojianhong 20220921 for 若依框架只会对startPage后第一个查询结果进行分页，对于处理后的list进行分页需要手工处理 start
        //startPage();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        //added by gaojianhong 20220921 for 若依框架只会对startPage后第一个查询结果进行分页，对于处理后的list进行分页需要手工处理 end

        List<ProjectPerson> list = projectPersonService.selectProjectPersonList(projectPerson);
        TableDataInfo tempResult = getDataTable(list);
        List<ProjectPersonVo> listResult=null;
        if(list!=null && list.size()>0) {
            List<Long>personIds = new ArrayList<>();
            list.forEach(pp->{
                personIds.add(pp.getPersonId());
            });
            Map<Long,Long>lockedMap = new HashMap<Long,Long>();
            List<ProjectPerson>lockedPersonList = projectPersonService.selectLockedStatusByPersonIds(personIds);

            if (lockedPersonList != null && lockedPersonList.size() > 0) {
                lockedPersonList.forEach(pp -> {
                    lockedMap.put(pp.getPersonId(), pp.getPersonId());
                });
            }

            listResult = list.stream().map(pp -> {
                ProjectPersonVo ppv = new ProjectPersonVo();
                ppv.setPersonId(pp.getPersonId());
                String personName = pp.getPersonName();
                ppv.setPersonName(personName);
                ppv.setLastName(personName != null && personName.length() > 0 ? personName.substring(personName.length() - 1) : "");
                String title = pp.getTitle();
                ppv.setTitle(title != null && title.length() > 0 ? DictUtils.getDictLabel("pm_person_title", title) : "");
                String personType = pp.getPersonType();
                if (personType != null && personType.length() > 0) {
                    String[] types = personType.split(",");
                    String voTypes = DictUtils.getDictLabel("pm_person_type", types[0]);
                    for (int i = 1; i < types.length; i++) {
                        voTypes = voTypes + "," + DictUtils.getDictLabel("pm_person_type", types[i]);
                    }
                    ppv.setPersonTypes(voTypes);
                }
                ppv.setCertifacates(pp.getJoinTime()!=null ? new SimpleDateFormat("yyyy-MM-dd").format(pp.getJoinTime()):"");

                if (lockedMap.get(ppv.getPersonId()) != null) {
                    ppv.setLocked(true);
                }

                return ppv;
            }).collect(Collectors.toList());

            if (projectPerson.getLocked()!=null && projectPerson.getLocked() ) {
                listResult.removeIf(pp_obj -> pp_obj.getLocked()==null);
            }
            if (projectPerson.getLocked()!=null && !projectPerson.getLocked() ) {
                listResult.removeIf(pp_obj -> pp_obj.getLocked()!=null && pp_obj.getLocked());
            }
        }
        //added by gaojianhong 20220921 for 若依框架只会对startPage后第一个查询结果进行分页，对于处理后的list进行分页需要手工处理 start
        //TableDataInfo result =getDataTable(listResult);
        //result.setTotal(tempResult.getTotal());
        int num = listResult.size();
        TableDataInfo result =new TableDataInfo();
        listResult = listResult.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        result.setCode(HttpStatus.SUCCESS);
        result.setMsg("查询成功");
        result.setRows(listResult);
        result.setTotal(num);
        //added by gaojianhong 20220921 for 若依框架只会对startPage后第一个查询结果进行分页，对于处理后的list进行分页需要手工处理 end
        return result;
    }
    @PreAuthorize("@ss.hasPermi('business:project_person:list')")
    @GetMapping("/applistFirst")
    public AjaxResult applistFirst(ProjectPerson projectPerson)
    {
        startPage();
        List<ProjectPerson> list = projectPersonService.selectProjectPersonList(projectPerson);
        TableDataInfo tempResult = getDataTable(list);

        Map<Long,Long>lockedMap = new HashMap<Long,Long>();
        if(list!=null && list.size()>0) {
            List<Long> personIds = new ArrayList<>();
            list.forEach(pp -> {
                personIds.add(pp.getPersonId());
            });
            List<ProjectPerson> lockedPersonList = projectPersonService.selectLockedStatusByPersonIds(personIds);

            if (lockedPersonList != null && lockedPersonList.size() > 0) {
                lockedPersonList.forEach(pp -> {
                    lockedMap.put(pp.getPersonId(), pp.getPersonId());
                });
            }
        }


        List<ProjectPersonVo> listResult = list.stream().map(pp -> {
            ProjectPersonVo ppv = new ProjectPersonVo();
            ppv.setPersonId(pp.getPersonId());
            String personName = pp.getPersonName();
            ppv.setPersonName(personName);
            ppv.setLastName(personName!=null && personName.length()>0 ?personName.substring(personName.length()-1):"");
            String title = pp.getTitle();
            ppv.setTitle(title!=null && title.length()>0?DictUtils.getDictLabel("pm_person_title",title):"");
            String personType = pp.getPersonType();
            if(personType!=null && personType.length()>0){
                String[]types = personType.split(",");
                String voTypes = DictUtils.getDictLabel("pm_person_type",types[0]);
                for (int i=1;i<types.length;i++) {
                    voTypes = voTypes+ ","+DictUtils.getDictLabel("pm_person_type",types[i]);
                }
                ppv.setPersonTypes(voTypes);
            }
            if (lockedMap.get(ppv.getPersonId()) != null) {
                ppv.setLocked(true);
            }
            ppv.setCertifacates(new SimpleDateFormat("yyyy-MM-dd").format(pp.getJoinTime()));
            return ppv;
        }).collect(Collectors.toList());
        Map<String,Object> result = new HashMap<>();
        TableDataInfo data = getDataTable(listResult);
        data.setTotal(tempResult.getTotal());
        result.put("data",data);
        result.put("typeCandidates",DictUtils.getDictLabels("pm_person_type"));
        result.put("titleCandidates",DictUtils.getDictLabels("pm_person_title"));
        return AjaxResult.success( result);
    }
    @GetMapping("/selectPMs")
    public AjaxResult selectPMs()
    {
        Map<String,Object> result = new HashMap<>();
        result.put("pms",projectPersonService.selectPMs());
        result.put("cascader",projectPersonService.getCascaderList());
        return AjaxResult.success( result);
    }
    @GetMapping("/check_person_name/{personName}")
    public AjaxResult checkPersonName(@PathVariable("personName")String personName)
    {
        return AjaxResult.success( projectPersonService.selectAuditorId(personName));
    }

    /**
     * 导出基本资料管理列表
     */
    @PreAuthorize("@ss.hasPermi('business:project_person:export')")
    @Log(title = "基本资料管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProjectPerson projectPerson)
    {
        List<ProjectPerson> list = projectPersonService.selectProjectPersonList(projectPerson);
        ExcelUtil<ProjectPerson> util = new ExcelUtil<ProjectPerson>(ProjectPerson.class);
        util.exportExcel(response, list, "基本资料管理数据");
    }

    /**
     * 获取基本资料管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:project_person:query')")
    @GetMapping(value = "/{personId}")
    public AjaxResult getInfo(@PathVariable("personId") Long personId)
    {
        return AjaxResult.success(projectPersonService.selectProjectPersonByPersonId(personId));
    }
    /**
     * 获取基本资料管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:project_person:query')")
    @GetMapping(value = "getAppInfo/{personId}")
    public AjaxResult getAppInfo(@PathVariable("personId") Long personId)
    {
        ProjectPerson projectPerson = projectPersonService.selectProjectPersonByPersonId(personId);
        if(projectPerson!=null){
            //人员类型
            String title = projectPerson.getTitle();
            projectPerson.setTitle(title!=null && title.length()>0?DictUtils.getDictLabel("pm_person_title",title):"");
            String personExternal = projectPerson.getExternalUnits();
            projectPerson.setExternalUnits(personExternal!=null && personExternal.length()>0?DictUtils.getDictLabel("pm_person_external",personExternal):"");
            String workStatus = projectPerson.getStatus();
            projectPerson.setStatus(workStatus!=null && workStatus.length()>0?DictUtils.getDictLabel("pm_person_work_status",workStatus):"");
            String personType = projectPerson.getPersonType();
            if(personType!=null && personType.length()>0){
                String[]types = personType.split(",");
                String voTypes = DictUtils.getDictLabel("pm_person_type",types[0]);
                for (int i=1;i<types.length;i++) {
                    voTypes = voTypes+ ","+DictUtils.getDictLabel("pm_person_type",types[i]);
                }
                projectPerson.setPersonType(voTypes);
            }
            String personMajor = projectPerson.getPersonMajor();
            if(personMajor!=null && personMajor.length()>0){
                String[]majors = personMajor.split(",");
                String voMajor = DictUtils.getDictLabel("pm_major",majors[0]);
                for (int i=1;i<majors.length;i++) {
                    voMajor = voMajor+ ","+DictUtils.getDictLabel("pm_person_type",majors[i]);
                }
                projectPerson.setPersonMajor(voMajor);
            }
            List<CurrentProject> projectList = currentProjectService.selectPersonProjectById(personId);
            if(projectList!=null && projectList.size()>0){
                projectList.forEach(o->{
                    o.setAppPersonType(DictUtils.getDictLabel("pm_person_type",o.getPersonType()));
                    o.setAppProjectType(o.getProjectType()==1?"业绩(历史)项目":"投标项目");
                });
                projectPerson.setPersonProjectList(projectList);
            }
        }
        return AjaxResult.success(projectPerson);
    }
    @PreAuthorize("@ss.hasPermi('business:project_person:query')")
    @GetMapping(value = "/get_person_by_type/{personType}")
    public AjaxResult selectPersonByType(@PathVariable("personType") String personType)
    {
        return AjaxResult.success(projectPersonService.selectPersonByType(personType));
    }

    /**
     * 新增基本资料管理
     */
    @PreAuthorize("@ss.hasPermi('business:project_person:add')")
    @Log(title = "基本资料管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProjectPerson projectPerson)
    {
        return toAjax(projectPersonService.insertProjectPerson(projectPerson));
    }

    /**
     * 修改基本资料管理
     */
    @PreAuthorize("@ss.hasPermi('business:project_person:edit')")
    @Log(title = "基本资料管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProjectPerson projectPerson)
    {
        return toAjax(projectPersonService.updateProjectPerson(projectPerson));
    }

    /**
     * 删除基本资料管理
     */
    @PreAuthorize("@ss.hasPermi('business:project_person:remove')")
    @Log(title = "基本资料管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{personIds}")
    public AjaxResult remove(@PathVariable Long[] personIds)
    {
        List<ProjectPerson>personList = projectPersonService.selectProjectPersonByPersonIds(personIds);
        if(personList!=null && personList.size()>0){
            StringBuilder sb = new StringBuilder();
            personList.forEach(p->{
                sb.append(p.getPersonName()).append(" ");
            });
            return AjaxResult.error(sb.toString()+"在项目中有关联，不能删除");
        }
        return toAjax(projectPersonService.deleteProjectPersonByPersonIds(personIds));
    }
}
